package com.ydl.partitionscheduler.strategy;

import com.ydl.partitionscheduler.config.TablePartitionProperties;
import com.ydl.partitionscheduler.model.PartitionInfo;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Component
public class HourlyPartitionStrategy implements PartitionStrategy {

    @Override
    public String getStrategyName() {
        return "hourly";
    }

    private static int HOURS = 24;

    @Override
    public List<PartitionInfo> generatePartitions(TablePartitionProperties.TablePartitionConfig config) {
        List<PartitionInfo> partitions = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(config.getValuePattern());
        for (int d = 0; d < config.getPreCreateCount(); d++) {
            // 起点：当天0点
            LocalDateTime dayStart = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
            dayStart = dayStart.plusDays(d);
            int divideCount = config.getDivideCount();
            if (HOURS % divideCount != 0) {
                throw new IllegalArgumentException("preCreateCount必须是24的约数（如2,3,4,6等），当前值：" + divideCount);
            }
            int size = HOURS / divideCount; // 每个分区的小时数（整数）

            for (int i = 0; i < divideCount; i++) {
                LocalDateTime partitionStart = dayStart.plusHours(i * size);
                LocalDateTime partitionEnd = partitionStart.plusHours(size);
                PartitionInfo partition = new PartitionInfo();
                partition.setPartitionName(config.getNamePattern()
                        .replace("${mainTable}", config.getMainTable())
                        .replace("${partitionSuffix}", partitionStart.format(DateTimeFormatter.ofPattern("yyyyMMddHH"))));
                // 起止值：使用配置的格式
                partition.setStartValue(partitionStart.format(formatter));
                partition.setEndValue(partitionEnd.format(formatter));

                partitions.add(partition);
            }
        }
        return partitions;
    }
}
